package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"post-master/cache"
	"post-master/models"
	"time"
)

func List(c *gin.Context) {
	var tz []models.Tz

	redis_key := "tz_list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Find(&tz)
		jsonData, _ := json.Marshal(tz)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &tz)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "列表查询成功",
		"data": tz,
	})
	return

}

func Detail(c *gin.Context) {
	id := c.Query("id")

	var tz models.Tz
	redis_key := "tz_detail" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.First(&tz)
		jsonData, _ := json.Marshal(tz)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &tz)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "详情查询成功",
		"data": tz,
	})
	return
}
